package com.minelx.woods.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.minelx.woods.data.values.InfoValues;
import com.minelx.woods.data.values.TaskValues;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

import static java.util.Collections.emptyList;

public class TasksHelper implements AutoCloseable {
	private final MongoClient client;

	private final MongoCollection<Document> tasksCollection;

	private final Tasks tasks;

	private final String firstTaskId;

	private final String secondTaskId;

	public TasksHelper() {
		client = new MongoClient("localhost", 27017);
		MongoDatabase testDB = client.getDatabase("testdb");
		tasksCollection = testDB.getCollection("tasks");

		InfoValues addedInfo = new InfoValues("sourceType", new JSONObject(), emptyList(), emptyList());

		tasks = new Tasks(tasksCollection);
		tasks.removeAll();
		firstTaskId = tasks.push(JSON.parseObject(JSON.toJSONString(addedInfo))).getId();
		secondTaskId = tasks.push(JSON.parseObject(JSON.toJSONString(addedInfo))).getId();
	}

	public TaskValues getFirstTaskValues() {
		return getFirstTask().values();
	}

	public Task getFirstTask() {
		return tasks.id(firstTaskId);
	}

	public TaskValues getSecondTaskValues() {
		return getSecondTask().values();
	}

	public Task getSecondTask() {
		return tasks.id(secondTaskId);
	}

	public MongoCollection<Document> getTasksCollection() {
		return tasksCollection;
	}

	public Tasks getTasks() {
		return tasks;
	}

	public MongoDatabase getDatabase() {
		return getClient().getDatabase("testdb");
	}

	public MongoClient getClient() {
		return client;
	}

	@Override
	public void close() {
		client.close();
	}
}
